package com.my.aslife.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.aslife.mapper.SfzMapper;
import com.my.aslife.module.common.*;
import com.my.aslife.module.entity.Ailyun;
import com.my.aslife.module.entity.Sfz;
import com.my.aslife.module.entity.User;
import com.my.aslife.module.entity.UserDetail;
import com.my.aslife.module.entity.dtos.*;
import com.my.aslife.service.EmailService;
import com.my.aslife.service.IUserService;
import com.my.aslife.service.UserDetailService;
import com.my.aslife.utils.HttpUtils;
import com.my.aslife.utils.MyCheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-12-12
 */
@Slf4j
@RestController
@RequestMapping("/api/my/user")
@CrossOrigin
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private UserDetailService userDetailService;


    @GetMapping("/normal/info")
    public ResponseResult getUserNormalByPage(@RequestParam Integer current, @RequestParam Integer pageSize,
                                                        @RequestParam(value = "phone", required = false) String phone,
                                                        @RequestParam(value = "email", required = false) String email) {

        Condition condition = new Condition(phone, email, new Short[]{10});
        PageRequestVo pageRequestVo = new PageRequestVo(current, pageSize, condition);
        log.info("查询条件 condition ==> {}", condition);

        return iUserService.getUserInfoByPage(pageRequestVo);
    }

    @GetMapping("/admin/info")
    public ResponseResult getUserAdminByPage(@RequestParam Integer current, @RequestParam Integer pageSize,
                                            @RequestParam(value = "phone", required = false) String phone,
                                            @RequestParam(value = "email", required = false) String email) {

        Condition condition = new Condition(phone, email, new Short[]{20, 21, 99});
        PageRequestVo pageRequestVo = new PageRequestVo(current, pageSize, condition);
        log.info("查询条件 condition ==> {}", condition);

        return iUserService.getUserInfoByPage(pageRequestVo);
    }

    @GetMapping("/runner/info")
    public ResponseResult getUserRunnerByPage(@RequestParam Integer current, @RequestParam Integer pageSize,
                                            @RequestParam(value = "phone", required = false) String phone,
                                            @RequestParam(value = "email", required = false) String email) {

        Condition condition = new Condition(phone, email, new Short[]{11});
        PageRequestVo pageRequestVo = new PageRequestVo(current, pageSize, condition);
        log.info("查询条件 condition ==> {}", condition);

        return iUserService.getUserInfoByPage(pageRequestVo);
    }


    @GetMapping("/illegal/info")
    public ResponseResult getUserIllegalByPage(@RequestParam Integer current, @RequestParam Integer pageSize,
                                            @RequestParam(value = "phone", required = false) String phone,
                                            @RequestParam(value = "email", required = false) String email) {

        Condition condition = new Condition(phone, email, (short) 1);
        PageRequestVo pageRequestVo = new PageRequestVo(current, pageSize, condition);
        log.info("查询条件 condition ==> {}", condition);

        return iUserService.getUserInfoByPage(pageRequestVo);
    }

    @GetMapping("/info/{id}")
    public ResponseResult<UserDto> queryUserById(@PathVariable(name = "id") Integer id) {

        User user = iUserService.queryUserById(id);

        ResponseResult<UserDetail> userDetailResponseResult = userDetailService.queryUserDetailInfoByUID(Long.valueOf(id));
        UserDetail userDetailDate = userDetailResponseResult.getData();

        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        if (userDetailDate != null) {
            BeanUtils.copyProperties(userDetailDate, userDto);
        }
        userDto.setTypeName(MyCheckUtils.typeToTypeName(userDto.getType()));

        return ResponseResult.ok(userDto);
    }

    @PutMapping("/change/status/{uid}")
    public ResponseResult changeUserStatus(@PathVariable Integer uid) {

        return iUserService.changeUserStatus(uid);
    }

    @DeleteMapping("/deletes")
    public ResponseResult deleteBatchByIds(@RequestBody String[] ids){

        if (ids == null || ids.length == 0) {
            return ResponseResult.failed(ErrorCode.C_PARAMS_NOT_NULL);
        }

        return iUserService.deleteBatchByIds(ids);
    }

    @PostMapping("/change/type")
    public ResponseResult changeUserType(@RequestBody UserTypeDto userTypeDto) {
        if (userTypeDto.getUid() == null || userTypeDto.getType() == null) {
            return ResponseResult.failed(ErrorCode.C_PARAMS_NOT_NULL);
        }

        return iUserService.changeUserType(userTypeDto);
    }

    @GetMapping("/send/email")
    public ResponseResult sendEmail(@RequestParam("to") String to){

        return emailService.sendRegisterEmail(to);
    }

    @PostMapping("/change/nick")
    public ResponseResult changeUserNickByUID(@RequestBody UserNickDto userNickDto){
        if (userNickDto.getUid() == null || userNickDto.getNickName() == null) {
            return ResponseResult.failed(ErrorCode.C_PARAMS_NOT_NULL);
        }
        return iUserService.changeUserNickByUID(userNickDto);
    }

    @PostMapping("/get/{uid}")
    public ResponseResult queryUserByUID(@PathVariable Long uid){
        return iUserService.queryUserInfoByUID(uid);
    }

    @PostMapping("/add/info")
    public ResponseResult addUserInfo(@RequestBody User user){
        return iUserService.addUserInfo(user);
    }

    @Autowired
    private SfzMapper sfzMapper;

    @PostMapping("/get/sfz/{uid}")
    public ResponseResult getSfzInfoByUID(@PathVariable Long uid) {
        LambdaQueryWrapper<Sfz> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Sfz::getUid, uid);
        Sfz sfz = sfzMapper.selectOne(lqw);
        return ResponseResult.ok(sfz);
    }


    @PostMapping("/sfz")
    public ResponseResult sfzCheck(@RequestBody UserSFZDto userSFZDto){
        String host = "https://idenauthen.market.alicloudapi.com";
        String path = "/idenAuthentication";
        String method = "POST";
        String appcode = "cdb3d0d998964004919918fd9a2ee623";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idNo", userSFZDto.getSfz());
        bodys.put("name", userSFZDto.getName());



        Ailyun ailyun = null;
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 0000     身份证信息匹配
             * 0001     开户名不能为空
             * 001      开户名不能包含特殊字符
             * 0003     身份证号不能为空
             * 0004     身份证号格式错误
             * 0007     无此身份证号码
             * 0008     身份证信息不匹配
             * 0010     系统维护，请稍后再试
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            String s = EntityUtils.toString(response.getEntity());

            ObjectMapper objectMapper = new ObjectMapper();
            ailyun = objectMapper.readValue(s, Ailyun.class);

            if (ailyun.getRespCode().equals("00000")) {

            } else {
                return ResponseResult.failed("1", ailyun.getRespMessage());
            }

            System.out.println(ailyun);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Sfz sfz = new Sfz();
        sfz.setSfz(userSFZDto.getSfz());
        sfz.setName(userSFZDto.getName());
        sfzMapper.insert(sfz);
        UserDetail userDetail = new UserDetail();
        LambdaQueryWrapper<UserDetail> lqwde = new LambdaQueryWrapper<>();
        lqwde.eq(UserDetail::getUid, userSFZDto.getUid());
        UserDetail one = userDetailService.getOne(lqwde);
        one.setSfzh(userSFZDto.getSfz());
        userDetailService.save(one);

        return ResponseResult.ok(ailyun);
    }

}
